/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest.front;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.bo.*;
import me.zhengjie.modules.system.bo.req.YplyReq;
import me.zhengjie.modules.system.domain.DccOss;
import me.zhengjie.modules.system.domain.DccOthersSb;
import me.zhengjie.modules.system.domain.DccUser;
import me.zhengjie.modules.system.repository.DccDuchachaXiangguanRepository;
import me.zhengjie.modules.system.service.DccOssService;
import me.zhengjie.modules.system.service.DccOthersSbService;
import me.zhengjie.modules.system.service.DccOthersService;
import me.zhengjie.modules.system.service.DccUserService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.DccDuchachaXiangguanMapper;
import me.zhengjie.modules.system.util.*;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SmsAliUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.bo.MllSms;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @website https://eladmin.vip
* @author cjl
* @date 2023-05-16
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "DCC图片识别相关管理")
@RequestMapping("/front/shibie")
public class FrontTupianShibieController {


    private final EntityManager entityManager;

    private final DccOssService dccOssService;
    private final DccOthersService dccOthersService;

    public static final String MLL_BUCKETNAME_LINE = "wb.user.cai";
    //直接sql查询     <select id="selectByRandom" resultMap="BaseResultMap"  >
//        select
//        *
//        from dcc_duchacha_xiangguan
//        WHERE    id >= (SELECT FLOOR( MAX(id) * RAND()) FROM drugle_question where `type` =  #{type,jdbcType=VARCHAR}) ORDER BY id LIMIT #{num,jdbcType=INTEGER}
    //  </select>
    //  select * from dcc_duchacha_xiangguan WHERE   id >= (SELECT FLOOR( MAX(id) * RAND()) FROM dcc_duchacha_xiangguan  ORDER BY id LIMIT 1)
    public  List<Map<String, Object>> listBySQL(String sql) {
        Query query = entityManager.createNativeQuery(sql);

        query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }
    private final DccOthersSbService dccOthersSbService;





    @Log("资讯列表")
    @ApiOperation("资讯列表")
    @AnonymousAccess
    @PostMapping(value = "/list")
    public ResponseEntity<Object> queryDccYaopinlanyong(@RequestBody DccOthersQueryCriteria yplyReq){
        List<DccOthersDto> dccOthersDtos = dccOthersService.queryAll(yplyReq);
        return new ResponseEntity<>(dccOthersDtos,HttpStatus.OK);
    }






    @Log("上传并返回识别后代码")
    @PostMapping("/ai")
    @AnonymousAccess
    @ApiOperation(value = "上传并返回识别后代码", httpMethod = "POST")
    public ResponseEntity<Object> sendAlert(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception{
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        //必须登录才能上传
        boolean login = StpUtil.isLogin();
       // JSONObject jsonObject=new JSONObject();
            Map jsonObject=new HashMap();
        String ai ="";
        if (login){
            DccOss dccOss=new DccOss();
            String fileName = file.getOriginalFilename();
            File dest=new File("/tmp/"+fileName);
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                log.error(e.toString(), e);
            }
            String currentDateTime = DateUtil.localDateTimeFormat(LocalDateTime.now(),DateUtil.DFY_MD_YY);
            String filePath="userInfo/"+StpUtil.getLoginId()+ "/"+ currentDateTime+dest.getName();
            try {
                OSSClientUtil.writeFileByFile(dest,filePath);
                //入库记录链接
                dccOss.setOperator(StpUtil.getLoginId().toString());
                dccOss.setUrl("https://rwoss.miaolianlian.com/"+filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String s=dest.getName();
            if ((s.length() - s.lastIndexOf("jpg"))==3||(s.length() - s.lastIndexOf("png"))==3||(s.length() - s.lastIndexOf("JPG"))==3||
                    (s.length() - s.lastIndexOf("webp"))==4||(s.length() - s.lastIndexOf("PNG"))==3||(s.length() - s.lastIndexOf("JPEG"))==4||
                    (s.length() - s.lastIndexOf("jpeg"))==4||(s.length() - s.lastIndexOf("gif"))==3||(s.length() - s.lastIndexOf("gif"))==3){
                //先识别文字，让后并列搜索，如果搜索到结果的话返回，搜索不到的话删除
                BaiDuV2Result aiV1 = BaiDuAiWenZiUtils.getAiV1(dest.getAbsolutePath());
                String returnWord="";
                if (!org.apache.commons.collections4.CollectionUtils.isEmpty(aiV1.getWords_result())){
                    for (WordsResult wordsResult:aiV1.getWords_result()){
                        if (wordsResult.getWords().length()<=2){
                            continue;
                        }
                        List<Map<String, Object>> maps = listBySQL("select * from dcc_others where name ='" + wordsResult + "'");
                        if (!CollectionUtils.isEmpty(maps)){
                            jsonObject.put("result","该物品属于毒品或易滥用药物");
                            jsonObject.put("resultDetail","请谨慎使用或者遵医嘱。");
                            break;
                        }else{
                            //记录数据最大的一个返回
                            if (StringUtils.isAllEmpty(returnWord)||returnWord.length()<wordsResult.getWords().length()){
                                returnWord=wordsResult.getWords();
                                jsonObject.put("result",returnWord+",非毒品或易滥用药物");
                            }
                            jsonObject.put("resultDetail","根据拍摄照片识别判断，该药物为非毒品或易滥用药物，可正常使用。");
                        }

                    }
                }else{
                    //识别，并获取百科api返回
                    List<ResultV1Detail> ai1 = BaiDuAiUtils.getAiV1(dest.getAbsolutePath());
                    dccOss.setContent(JSON.toJSONString(ai1));
                    ai=ai1.get(0).getKeyword();
//                AliResult cidian = CidianUtil.getCidian(ai);
                    dccOss.setContentBaike(JSON.toJSONString(ai1.get(0).getBaike_info()));
                    dccOss.setIp(IPUtils.getRemortIP(request));
//                    jsonObject.put("basic",ai);
//                    jsonObject.put("basicDetail",ai1.get(0).getBaike_info().getDescription());
                    DccOthersQueryCriteria dccOthersQueryCriteria=new DccOthersQueryCriteria();
                    dccOthersQueryCriteria.setName(ai);
                    List<DccOthersDto> dccOthersDtos = dccOthersService.queryAll(dccOthersQueryCriteria);
                    if (!CollectionUtils.isEmpty(dccOthersDtos)){
                        jsonObject.put("result","该物品属于毒品或易滥用药物");
                        jsonObject.put("resultDetail","请谨慎使用或者遵医嘱。");
                    }else{
                        jsonObject.put("result",ai1.get(0).getKeyword()+",非毒品或易滥用药物");
                        jsonObject.put("resultDetail","根据拍摄照片识别判断，该药物为非毒品或易滥用药物，可正常使用。");
                    }

                }

                List<Map<String, Object>> maps = listBySQL("  select * from dcc_duchacha_xiangguan WHERE   id >= (SELECT FLOOR( MAX(id) * RAND()) FROM dcc_duchacha_xiangguan  ORDER BY id LIMIT 1)");
                jsonObject.put("xiangguan",maps.get(0));
            }
            dest.delete();
            dccOss.setType("图片识别");
            dccOssService.create(dccOss);
        }else{
            jsonObject.put("result","未登录");
            return new ResponseEntity<>(jsonObject,HttpStatus.BAD_GATEWAY);
        }
        return new ResponseEntity<>(jsonObject,HttpStatus.OK);
    }



    @Log("上传并返回识别后代码")
    @PostMapping("/aiV1")
    @AnonymousAccess
    @ApiOperation(value = "上传并返回识别后代码", httpMethod = "POST")
    public ResponseEntity<Object> aiV1(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception{
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        //必须登录才能上传
        boolean login = StpUtil.isLogin();
        // JSONObject jsonObject=new JSONObject();
        Map jsonObject=new HashMap();
        String ai ="";
        if (login){
            DccOss dccOss=new DccOss();
            String fileName = file.getOriginalFilename();
            File dest=new File("/tmp/"+fileName);
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                log.error(e.toString(), e);
            }
            String currentDateTime = DateUtil.localDateTimeFormat(LocalDateTime.now(),DateUtil.DFY_MD_YY);
            String filePath="userInfo/"+StpUtil.getLoginId()+ "/"+ currentDateTime+dest.getName();
            try {
                OSSClientUtil.writeFileByFile(dest,filePath);
                //入库记录链接
                dccOss.setOperator(StpUtil.getLoginId().toString());
                dccOss.setUrl("https://rwoss.miaolianlian.com/"+filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String s=dest.getName();
            jsonObject.put("name","无法比对");
            jsonObject.put("resultDetail","无法通过图片进行比对，请自行通过首页-毒品类目功能查询。");
            if ((s.length() - s.lastIndexOf("jpg"))==3||(s.length() - s.lastIndexOf("png"))==3||(s.length() - s.lastIndexOf("JPG"))==3||
                    (s.length() - s.lastIndexOf("webp"))==4||(s.length() - s.lastIndexOf("PNG"))==3||(s.length() - s.lastIndexOf("JPEG"))==4||
                    (s.length() - s.lastIndexOf("jpeg"))==4||(s.length() - s.lastIndexOf("gif"))==3||(s.length() - s.lastIndexOf("gif"))==3){
                //先识别文字，让后并列搜索，如果搜索到结果的话返回，搜索不到的话删除
                BaiDuV2Result aiV1 = BaiDuAiWenZiUtils.getAiV1(dest.getAbsolutePath());
                String returnWord="";
                String zhunzi="";
                String name="";
                String yaopinmingcheng="";
                String resultDetail= "根据图片比对识别，该药物含有管制成分，属于国家规定管制的非药用类麻醉药品和精神药品，请遵医嘱使用。";

                if (!org.apache.commons.collections4.CollectionUtils.isEmpty(aiV1.getWords_result())){
                    for (WordsResult wordsResult:aiV1.getWords_result()){
                            if (wordsResult.getWords().contains("国药准字")){
                                zhunzi=wordsResult.getWords();
                            }
                    }
                    for (WordsResult wordsResult:aiV1.getWords_result()){
                        if (wordsResult.getWords().length()<=2){
                            continue;
                        }

                        String sql="select * from dcc_others_sb where   name like '%" + wordsResult.getWords() + "%'";
                        System.out.println(sql);
                        List<Map<String, Object>> maps = listBySQL(sql);
                        if (!CollectionUtils.isEmpty(maps)){
                            jsonObject.put("name",maps.get(0).get("type"));
                            jsonObject.put("yaopinmingcheng",maps.get(0).get("name"));
                            jsonObject.put("zhunzi",StringUtils.isAllEmpty(zhunzi)?maps.get(0).get("guoyao"):zhunzi);
                            jsonObject.put("resultDetail","根据图片比对识别，该药物含有管制成分，属于国家规定管制的"+maps.get(0).get("type")+"，请遵医嘱使用。");
                            break;
                        }else{
                            jsonObject.put("name","无法比对");
//                            jsonObject.put("yaopinmingcheng","无法比对数据库");
                            jsonObject.put("resultDetail","无法通过图片进行比对，请自行通过首页-毒品类目功能查询。");
                       }


                    }
                }else{
                    jsonObject.put("name","无法比对");
//                    jsonObject.put("yaopinmingcheng","无法比对数据库");
                    jsonObject.put("resultDetail","无法通过图片进行比对，请自行通过首页-毒品类目功能查询。");
                }

            }
            dest.delete();
            dccOss.setType("图片识别");
            dccOssService.create(dccOss);
        }else{
            jsonObject.put("result","未登录");
            return new ResponseEntity<>(jsonObject,HttpStatus.BAD_GATEWAY);
        }
        return new ResponseEntity<>(jsonObject,HttpStatus.OK);
    }


}